package com.hi5.stexviewer.rates.bet;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hi5.stexviewer.domain.Market;
import com.hi5.stexviewer.domain.Rate;
import com.hi5.stexviewer.domain.Stock;
import com.hi5.stexviewer.rates.RateFetcher;

/**
 * Fetch data from Budapesti Ertek Tozsde (BET). <i>In its present state it
 * can't gather history.</i>
 * <p>
 * Source: http://bet.hu/ajaxdata?pid=AJI1004_1104 and
 * http://bet.hu/ajaxdata?pid=AJI1004_1105.
 *
 * @author mate
 *
 */
public class BetRateFetcher implements RateFetcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(BetRateFetcher.class);

    private static final String BET_A_URL = "http://bet.hu/ajaxdata?pid=AJI1004_1104";
    private static final String MARKET_NAME = "BET";

    public Map<Stock, List<Rate>> getRates(List<Stock> stocks, Date start) {
        Map<Stock, List<Rate>> result = null;

        Document doc = null;
        try {
            doc = Jsoup.connect(BET_A_URL).get();
        } catch (IOException e) {
            LOGGER.error("Cannot download data", e);
        }

        if (doc != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Response XML: {}", doc.html());
            }

            result = new HashMap<Stock, List<Rate>>();
            Elements trs = doc.select("root tbody").first().select("tr");
            Elements names = trs.select("td:eq(0)");

            for (Stock stock : stocks) {
                Rate rate = null;
                // Warning: This is not safe!
                Element current = names.select(":contains(" + stock.getName() + ")").first();
                if (current != null) {
                    Element priceElement = current.parent().select("td:eq(18)").first();
                    if (priceElement != null) {
                        String priceString = priceElement.text().replaceAll("\\D+", "");
                        try {
                            BigDecimal price = new BigDecimal(priceString);
                            rate = new Rate();
                            rate.setStock(stock);
                            rate.setRate(price);
                            rate.setDate(start);
                        } catch (NumberFormatException numberFormatException) {
                            LOGGER.info("Could not parse '{}' as BigDecimal for {}", priceString, stock.getName());
                        }
                    }
                }

                List<Rate> rates;
                if (rate == null) {
                    rates = Collections.emptyList();
                } else {
                    rates = new ArrayList<Rate>(1);
                    rates.add(rate);
                }
                result.put(stock, rates);
            }
        }

        return result;
    }

    public boolean supports(Market market) {
        return MARKET_NAME.equals(market.getName());
    }

}
